package com.zhl.model.excel.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.zhl.common.annotation.ApiIdempotent;
import com.zhl.common.annotation.NoRepeatSubmit;
import com.zhl.common.vo.Result;
import com.zhl.model.email.service.MailService;
import com.zhl.model.email.service.TokenService;
import com.zhl.model.excel.entity.BiddingProjectVo;
import com.zhl.model.excel.entity.DictVo;
import com.zhl.model.excel.service.ExcelStyleUtil;
import com.zhl.model.excel.service.ExportOnlineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author zhl
 * @Title: ExportOnlineController
 * @Description TODO
 * @date： 2020/9/17 13:39
 * @version： V1.0
 */
@RestController
@RequestMapping("/export")
@Slf4j
public class ExportOnlineController {

    @Autowired
    private ExportOnlineService exportOnlineService;

    @Autowired
    private MailService mailService;

    @Value("${mail.receiveEmail.addr}")
    private String receiveEmail;

    @Value("${report.localPath.temp}")
    private String filePath;

    @Autowired
    private TokenService tokenService;

    /**
     * 导出excel
     * @param lxsj 立项时间
     * @param dljgbh 招标代理机构
     * @return
     */
    @GetMapping("/exportOnline")
    public Result exportOnline(@RequestParam(value = "lxsj",required = true) String lxsj,
                               @RequestParam(value = "dljgbh",required = true) String dljgbh){
        String currentDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        ExcelWriter writer = ExcelUtil.getBigWriter("C:\\Users\\zhl\\Desktop\\导出\\exportOnline_"+currentDate+".xls");
        Map<String, Object> parameterSource = new HashMap<>();
        parameterSource.put("lxsj", lxsj);
        parameterSource.put("dljgbh", dljgbh);
        parameterSource.put("lybz", Arrays.asList(1,2));
        List<BiddingProjectVo> biddingProjectVoList = exportOnlineService.queryProjectInfo(parameterSource);
        writer.addHeaderAlias("projectName","项目名称");
        writer.setColumnWidth(1,55);
        writer.setColumnWidth(1,25);
        ExcelWriter write = writer.write(biddingProjectVoList);
        write.flush();
        return Result.ok();
    }

    /**
     * 导出excel
     * @param lxsj 立项时间
     * @param dljgbh 招标代理机构
     * @return
     */
    @GetMapping("/easyPoiExport")
    public Result easyPoiExport(@RequestParam(value = "lxsj",required = true) String lxsj,
                               @RequestParam(value = "dljgbh",required = true) String dljgbh){
        long startTime = System.currentTimeMillis();
        String currentDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        Map<String, Object> parameterSource = new HashMap<>();
        parameterSource.put("lxsj", lxsj);
        parameterSource.put("dljgbh", dljgbh);
        parameterSource.put("lybz", Arrays.asList(1,2));
        List<BiddingProjectVo> biddingProjectVoList = exportOnlineService.queryProjectInfo(parameterSource);
        ExportParams exportParams = new ExportParams("国际报表","全流程项目统计表");
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams,
                BiddingProjectVo.class, biddingProjectVoList);
        FileOutputStream fos = null;
        String fileName = filePath + "exportOnline_"+currentDate+".xlsx";
        try {
            fos = new FileOutputStream(fileName);
            workbook.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
                //重复导出失败，每次关闭这个即可Stream closed
                ExcelExportUtil.closeExportBigExcel();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("导出excel耗时==="+(System.currentTimeMillis()-startTime)+"毫秒");
        log.info("发送到邮箱==============="+receiveEmail);
        mailService.sendAttachmentsMail(receiveEmail, "主题：国际全流程项目统计", "国际全流程项目统计，请查收！", fileName);
        log.info("************************统计国际全流程项目定时任务结束************************");
        return Result.ok();
    }

    @GetMapping("/dict")
    public Result queryDict(@RequestParam(value = "dictCodeList") List<String> dictCodeList){
        List<DictVo> dictList = exportOnlineService.queryDict(dictCodeList);
        return Result.ok(dictList);
    }

    @GetMapping("/test")
    @NoRepeatSubmit(lockTime = 100)
//    @ApiIdempotent
    public Result test(){
        return Result.ok();
    }

    @GetMapping("/createToken")
    public Result token() {
        return tokenService.createToken();
    }

}
